//
// Created by Administrator on 2021/1/31 0031.
//

#ifndef JQHMUSIC_JQHAUDIO_H
#define JQHMUSIC_JQHAUDIO_H

#include "JqhQueue.h"
#include "JqhPlayStatus.h"
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
#include "CallJava.h"
#include "SoundTouch.h"
#include <libavutil/time.h>
extern "C"{
    #include <libavutil/time.h>
};
using namespace soundtouch;


extern "C" {
#include "libavcodec/avcodec.h"
#include "libswresample/swresample.h"
};


class JqhAudio {

public:
    int streamIndex = -1;
    AVCodecParameters *codecpar = NULL;
    AVCodecContext *avCodecContext = NULL;
    JqhQueue *queue = NULL;
    JqhPlayStatus *playStatus = NULL;
    CallJava *callJava = NULL;
    pthread_t  thread_play;
    AVPacket *avPacket;
    AVFrame *avFrame;
    int ret = -1;
    uint8_t *buffer = NULL;
    int data_size = 0;
    int sample_rate = 0;

    int duration = 0 ;
    AVRational time_base;
    double now_time = 0;
    double clock = 0;
    double last_time = 0;
    int volumePercent = 100;
    int mute = 2;

    // 以下是测试播放pcm的代码
    SLObjectItf engineObject = NULL;
    SLEngineItf engineEngine = NULL;
//混音器
    SLObjectItf outputMixObject = NULL;
    SLEnvironmentalReverbItf outputMixEnvironmentalReverb = NULL;
    SLEnvironmentalReverbSettings reverbSettings = SL_I3DL2_ENVIRONMENT_PRESET_STONECORRIDOR;

    SLObjectItf pcmPlayerObject = NULL;
    SLPlayItf pcmPlayerPlay = NULL;
    SLVolumeItf pcmPlayerVolume = NULL;
    SLMuteSoloItf  pcmMutePlay = NULL;

//缓冲器队列接口
    SLAndroidSimpleBufferQueueItf pcmBufferQueue;

    SoundTouch *soundTouch = NULL;
    SAMPLETYPE  *sampleBuffer = NULL;
    bool  finished = true;
    uint8_t  *out_buffer = NULL;
    int nb = 0 ;
    int num = 0 ; //  变速的采样个数
    float pitch = 1.0f;
    float speed = 1.0f;
    bool  isRecordPcm = false;
    bool readFrameFinished = true;

public:
    JqhAudio(JqhPlayStatus *playStatus, int sample_rate, CallJava *callJava);
    ~JqhAudio();
    void play();
    int resumpleAudio(void **pcmbuf);
    void initOpenSLES();

    int getCurrentSampleRateForOpensles(int sample_rate);

    void pause();

    void resume();

    void stop();

    void release();

    void setVolume(int percent);

    void setMute(int mute);

    int getSoundTouchData();
    void setPitch(float pitch);
    void setSpeed(float speed);

    int getPCMDB(char *pcmdata, size_t pcmsize);

    void startStopRecord(bool start);

};


#endif //JQHMUSIC_JQHAUDIO_H
